package com.example.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

public class MyProvider extends ContentProvider {

	MyHelper dbhelper;
	static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
	
	static {
		matcher.addURI("com.example.provider.hello", "student", 1);
		matcher.addURI("com.example.provider.hello", "teacher", 2);
	}

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		dbhelper = new MyHelper(getContext());
		return true;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		SQLiteDatabase sd=dbhelper.getWritableDatabase();
		int delete=0;
		switch(matcher.match(uri)){
			case 1:
				delete=sd.delete("student", selection, selectionArgs);
				break;
			case 2:
				delete=sd.delete("teacher", selection, selectionArgs);
				break;
		}
		return 0;
	}
	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase sd=dbhelper.getWritableDatabase();
		Uri uriReturn=null;
		switch(matcher.match(uri)){
			case 1:
				sd.insert("student", null, values);
				uriReturn=Uri.parse("content://"+"com.example.provider.hello"+"/student/");
				break;
			case 2:
				sd.insert("teacher", null, values);
				uriReturn=Uri.parse("content://"+"com.example.provider.hello"+"/teacher/");
				break;
			default:
				break;
		}
		return uriReturn;
	}

	@Override
	public Cursor query(Uri uri, String[] projection,String selection,String[] selectionArgs, String sortOrder) {
		SQLiteDatabase sd=dbhelper.getReadableDatabase();
		Cursor cursor=null;
		switch(matcher.match(uri)){
			case 1:
				cursor=sd.query("student", projection, selection, selectionArgs, null, null, sortOrder);
				break;
			case 2:
				cursor=sd.query("teacher", projection, selection, selectionArgs, null, null, sortOrder);
			    break;
			default:
				break;
		}
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		SQLiteDatabase sd=dbhelper.getWritableDatabase();
		int update=0;
		switch(matcher.match(uri)){
			case 1:
				update=sd.update("student", values, selection, selectionArgs);
				break;
			case 2:
				update=sd.update("teacher", values, selection, selectionArgs);
				break;
		}
		return update;
	}

}
